<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.id ? '新增兑换券' : '修改兑换券'"
    :close-on-click-modal="false"
    width="600px"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="100px"
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        label="兑换券名称"
        prop="name"
      >
        <el-input
          v-model="dataForm.name"
          placeholder="请输入兑换券名称"
        />
      </el-form-item>

      <el-form-item
        label="课程"
        prop="courseId"
      >
        <el-select
          v-model="dataForm.courseId"
          placeholder="请选择关联的课程（可选）"
          clearable
          filterable
          remote
          :remote-method="remoteCourseSearch"
          :loading="courseLoading"
        >
          <el-option
            v-for="item in courseList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        label="地区"
        prop="areaId"
      >
        <el-cascader
          v-model="selectedArea"
          expand-trigger="hover"
          :options="areaList"
          :props="areaProps"
          change-on-select
          clearable
          @change="handleAreaChange"
        />
      </el-form-item>

      <el-form-item
        label="状态"
        prop="status"
      >
        <el-select
          v-model="dataForm.status"
          placeholder="请选择状态"
        >
          <el-option
            label="未使用"
            :value="1"
          />
          <el-option
            label="已使用"
            :value="2"
          />
          <el-option
            label="已过期"
            :value="3"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        label="过期时间"
        prop="expiredAt"
      >
        <el-date-picker
          v-model="dataForm.expiredAt"
          type="datetime"
          placeholder="请选择过期时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>

      <el-form-item
        v-if="dataForm.id"
        label="兑换码"
        prop="exchangeCode"
      >
        <el-input
          v-model="dataForm.exchangeCode"
          disabled
          placeholder="系统自动生成"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button
          type="primary"
          @click="onSubmit()"
        >确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { Debounce } from '@/utils/debounce.js'

const emit = defineEmits(['refreshDataList'])
const visible = ref(false)

// eslint-disable-next-line no-unused-vars
const validateName = (rule, value, callback) => {
  if (!value || !value.trim()) {
    dataForm.value.name = ''
    callback(new Error('兑换券名称不能为空'))
  } else {
    callback()
  }
}

// eslint-disable-next-line no-unused-vars
const validateExpiredAt = (rule, value, callback) => {
  if (!value) {
    callback(new Error('过期时间不能为空'))
  } else {
    callback()
  }
}

// eslint-disable-next-line no-unused-vars
const validateStatus = (rule, value, callback) => {
  if (value === null || value === undefined) {
    callback(new Error('状态不能为空'))
  } else {
    callback()
  }
}

const dataRule = {
  name: [
    { required: true, message: '兑换券名称不能为空', trigger: 'blur' },
    { validator: validateName, trigger: 'blur' }
  ],
  expiredAt: [
    { required: true, message: '过期时间不能为空', trigger: 'change' },
    { validator: validateExpiredAt, trigger: 'change' }
  ],
  status: [
    { required: true, message: '状态不能为空', trigger: 'change' },
    { validator: validateStatus, trigger: 'change' }
  ]
}

const dataForm = ref({
  id: null,
  name: null,
  courseId: null,
  provinceId: null,
  cityId: null,
  areaId: null,
  exchangeCode: null,
  status: 1,
  expiredAt: null
})

const dataFormRef = ref(null)

// 课程相关
const courseList = ref([])
const courseLoading = ref(false)

// 地区相关
const selectedArea = ref([])
const areaList = ref([])
const areaProps = {
  value: 'areaId',
  label: 'areaName',
  children: 'children'
}

const init = (id) => {
  dataForm.value.id = id || null
  visible.value = true
  selectedArea.value = []

  // 初始化地区数据
  initAreaData()
  // 初始化课程列表
  initCourseList()

  nextTick(() => {
    dataFormRef.value?.resetFields()
    if (dataForm.value.id) {
      http({
        url: http.adornUrl('/admin/exchangeVoucher/info/' + dataForm.value.id),
        method: 'get',
        params: http.adornParams()
      })
        .then(({ data }) => {
          dataForm.value = data
          // 设置级联选择器的值
          if(data.provinceId === 0) selectedArea.value = [0]
          if (data.provinceId || data.cityId || data.areaId) {
            selectedArea.value = [data.provinceId, data.cityId, data.areaId].filter(v => v)
          }
        })
    }
  })
}

/**
 * 初始化地区数据 - 使用 /admin/area/tree 接口获取完整树状结构
 */
const initAreaData = () => {
  http({
    url: http.adornUrl('/admin/area/tree'),
    method: 'get',
    params: http.adornParams()
  })
    .then(({ data }) => {
      // 将 areas 字段转换为 children 字段以适配级联选择器
      const transformAreaTree = (areas) => {
        return areas.map((area) => ({
          ...area,
          children: area.areas ? transformAreaTree(area.areas) : []
        }))
      }

      const areaData = data ? transformAreaTree(data) : []
      // 在最前面添加"不限制"选项
      areaList.value = [
        {
          areaId: 0,
          areaName: '不限制',
          children: []
        },
        ...areaData
      ]
    })
}

/**
 * 初始化课程列表
 */
const initCourseList = () => {
  http({
    url: http.adornUrl('/admin/course/page'),
    method: 'get',
    params: http.adornParams({ current: 1, size: 100 })
  })
    .then(({ data }) => {
      courseList.value = data.records || []
    })
}

/**
 * 远程搜索课程
 */
const remoteCourseSearch = (query) => {
  if (query) {
    courseLoading.value = true
    http({
      url: http.adornUrl('/admin/course/page'),
      method: 'get',
      params: http.adornParams({ current: 1, size: 100, title: query })
    })
      .then(({ data }) => {
        courseList.value = data.records || []
        courseLoading.value = false
      })
      .catch(() => {
        courseList.value = []
        courseLoading.value = false
      })
  } else {
    // 清空搜索时，重新加载完整列表
    initCourseList()
  }
}

/**
 * 处理地区级联选择变化
 */
const handleAreaChange = (value) => {
  if (value && value.length > 0) {
    dataForm.value.provinceId = value[0] || 0
    dataForm.value.cityId = value[1] || 0
    dataForm.value.areaId = value[2] || 0
  } else {
    dataForm.value.provinceId = 0
    dataForm.value.cityId = 0
    dataForm.value.areaId = 0
  }
}

defineExpose({ init })

/**
 * 表单提交
 */
const onSubmit = Debounce(() => {
  dataFormRef.value?.validate((valid) => {
    console.log("dataForm", dataForm)
    if (valid) {
      http({
        url: http.adornUrl('/admin/exchangeVoucher'),
        method: dataForm.value.id ? 'put' : 'post',
        data: http.adornData(dataForm.value)
      })
        .then(() => {
          ElMessage({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              visible.value = false
              emit('refreshDataList')
            }
          })
        })
    }
  })
})
</script>

<style lang="scss" scoped>
</style>

